package com.skydonkey.controller;


import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.skydonkey.dao.VideoInfoMapper;
import com.skydonkey.pojo.po.VideoInfo;
import com.skydonkey.pojo.po.VideoSampleResponse;
import com.skydonkey.pojo.po.VideoSamples;
import com.skydonkey.pojo.vo.Result;
import com.skydonkey.service.VideoSampleListener;
import com.skydonkey.service.VideoSampleService;
import com.skydonkey.utils.ObjectMapperUtil;
import com.skydonkey.utils.QiniuUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/api")
public class QiniuCallbackController {

    private static final Logger log = LoggerFactory.getLogger(QiniuCallbackController.class);

    @Autowired
    QiniuUtils qiniuUtils;

    @Autowired
    VideoSampleService videoSampleService;

    @Autowired
    VideoInfoMapper videoInfoMapper;

    @Autowired
    VideoSampleListener listener;

//    @RequestMapping(value = "/1", method = RequestMethod.GET)
//    public String test() {
//        return "hello ";
//    }
//
//    @RequestMapping(value="/2", method = RequestMethod.GET)
//    public String test2(){
//        Auth auth = qiniuUtils.getQiniuProperties().getAuth();
//        Configuration cfg = new Configuration();
//        // 实例化一个BucketManager对象
//        BucketManager bucketManager = new BucketManager(auth, cfg);
//
//        // 要测试的空间和key，并且这个key在你空间中存在
//        String bucket = qiniuUtils.getQiniuProperties().getBucket();
//        String key = "4291eeeb-9b29-4619-9f6a-920382e424a9.mp4";
//
//        // 调用stat()方法获取文件的信息
//        try {
//            FileInfo fileInfo = bucketManager.stat(bucket, key);
//            System.out.println(fileInfo.hash);
//            System.out.println(fileInfo.fsize);
//            System.out.println(fileInfo);
//            // 你可以根据返回的信息获取时长，或者调用其他API获取更多信息
//        } catch (QiniuException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    @RequestMapping(value = "/sample", method = RequestMethod.GET)
    public String generateSample() {
        List<VideoInfo> list = videoInfoMapper.findAll().getResult();
        for (VideoInfo info : list) {
            log.info(info.toString());
            listener.generateSample(info.getVideoId(), info.getVideoKey(), 10);
        }
        return "success";
    }

    // 给七牛的回调
    @RequestMapping(value = "/qiniu/callback", method = RequestMethod.POST)
    public String handleQiniuCallback(HttpServletRequest request, @RequestBody String payload) {
        System.out.println("payload = {}" + payload);
        // 获取七牛云的签名
        String authorization = request.getHeader("Authorization");
        // 验证签名
        if (!qiniuUtils.getQiniuProperties().getAuth().isValidCallback(
                authorization,
                "/api/qiniu/callback",
                payload.getBytes(),
                "application/x-www-form-urlencoded")) {
            // 签名无效，返回错误响应
        }
        VideoSampleResponse response = ObjectMapperUtil.toObject(payload, VideoSampleResponse.class);
        if (response == null) {
            return null;
        }

        List<VideoSamples> list = new ArrayList<>();
        String videoKey = response.getInputKey();

        for (VideoSampleResponse.Item item : response.getItems()) {
            List<String> sampleKeys = item.getKeys();
            for (String key : sampleKeys) {
                String sampleUrl = "http://" + qiniuUtils.getQiniuProperties().getBucketDomain() + "/" + key;
                VideoSamples videoSample = new VideoSamples()
                        .setVideoKey(videoKey)
                        .setSampleKey(key)
                        .setSampleUrl(sampleUrl);
                list.add(videoSample);
                log.info(videoSample.toString());
            }
        }
        videoSampleService.delete(videoKey);
        videoSampleService.addVideoSamples(list);
        // 这里去通知用户缩略图已经生成
        //            rabbitTemplate.convertAndSend(
        //                    RabbitConfig.CONVERSION_EXCHANGE_NAME,
        //                    RabbitConfig.CONVERSION_MP4_TO_FLV_ROUTING_KEY,
        //                    videoData);`
        return "{\"success\":true}";
    }

    /**
     * 测试阶段，手动补偿没有生成封面的视频
     */
    @RequestMapping(value = "/sample/{videoId}/{videoKey}", method = RequestMethod.GET)
    public Result<String> generateSamples(
            @PathVariable("videoId") Long videoId,
            @PathVariable("videoKey") String videoKey
    ) {
        listener.generateSample(videoId, videoKey, 10);
        return Result.success("success:" + videoId.toString());
    }
}
